package biblioteca.controlador;

import biblioteca.persistencia.Sancion;
import org.springframework.stereotype.Controller;
import biblioteca.persistencia.Socio;
import biblioteca.servicio.SocioServicio;
import java.util.Collection;
import java.util.Iterator;
import javax.servlet.http.HttpSession;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

@Controller
@SessionAttributes("socio")
public class SocioControlador {

    private SocioServicio socioServicio;
    private AuthenticationManager authenticationManager ;

    @Autowired
    @Required
    public void setSocioServicio(SocioServicio socioServicio) {
        this.socioServicio = socioServicio;
    }

    @PreAuthorize("isAdmin()")
    @RequestMapping(value = "/ir_altaSocio", method = RequestMethod.GET)
    public String goAltaSocio() {//para ir a la JSP
        System.out.println("entraaa JSP");
        return "/altaSocio";//este es el JSP
    }

    @PreAuthorize("isAdmin()")
    @RequestMapping(value = "/agregaSocio", method = RequestMethod.POST)
    public String doAgregarUsuario(@RequestParam("email") String email, @RequestParam("nombre") String nombre, @RequestParam("dni") String dni, @RequestParam("apellidos") String apellidos, @RequestParam("edad") String edad) {

        System.out.println("entrando a agregar nuevo socio");

        if ((email == null || email.length() == 0) && (nombre == null || nombre.length() == 0) && (dni == null || dni.length() == 0)) {
            return "/contruccion";//es temporal
        } else {
            final Socio socio = new Socio(dni, nombre, apellidos, edad, email);
            socioServicio.create(socio);
            System.out.println("el usuario numero " + socio.getId() + " agregado a la base de datos");
            return "/menu_inicio";
        }
    }
    
    @PreAuthorize("isAdmin()")
    @RequestMapping(value = "/sancionar", method = RequestMethod.GET)
    public String doSancion(@RequestParam("dni") String dni) {//para ir a la JSP
        Collection<Socio> lista_so = socioServicio.getAllSocios();
        Iterator it = lista_so.iterator();
        while (it.hasNext()) {
            Socio clave = (Socio) it.next();
            if (clave.getDni().compareTo(dni) == 0) {
                Sancion nuev = new Sancion();
                clave.getSanciones().add(nuev);
            } else {
                System.out.println("socio no encontrado, sancion no asignada");
            }
        }
        return "/altaSocio";//este es el JSP
    }

    @PreAuthorize("isAdmin()")
    @RequestMapping(value = "/listar_socios", method = RequestMethod.POST)
    public String goListaSocios() {//para ir a la JSP
        System.out.println("entraaa a Listar");
        return "/listadoP";//este es el JSP
    }

    @RequestMapping(method=RequestMethod.GET, value="/getUsuarioConectado", headers="Accept=application/json")
    public @ResponseBody Socio getUser() {
        return socioServicio.getCurrentUser();
    }

    @RequestMapping(method = RequestMethod.GET, value = "/logout")
    public String logout(HttpSession sesion, SessionStatus sessionStatus, @ModelAttribute("usuario") Socio socio) throws java.io.IOException {
        System.out.println("UsuarioController logout se está desconectando " + socio.getEmail());
        SecurityContextHolder.getContext().setAuthentication(null);
        Socio u = (Socio) sesion.getAttribute("usuario");
        System.out.println("UsuarioController logout se está desconectando2 " + socio.getEmail());
        sessionStatus.setComplete();
        //Otra forma: sesion.invalidate();

        return "redirect:index.html";
    }

    @RequestMapping(method = RequestMethod.GET, value = "/getLoginURL")//para ir a loguearse
    public String irLoginURL() {
        return "/login";
    }

    @RequestMapping(method = RequestMethod.GET, value = "/login", headers = "Accept=application/json")
    public @ResponseBody String login(@RequestParam String username, @RequestParam String password,
           Model model) {
        String rdo = null;
        try {
            //System.out.println("AQUI 1 UserController login ");
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            //System.out.println("AQUI 2 UserController login ");
            UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(username, password);
            //System.out.println("AQUI 3 UserController login ");
            authToken.setDetails(authentication.getDetails());
            //System.out.println("AQUI 4 UserController login authenticationManager="+authenticationManager);
            Authentication newAuth = authenticationManager.authenticate(authToken);
            //System.out.println("AQUI 5 UserController login ");
            SecurityContextHolder.getContext().setAuthentication(newAuth);
            //System.out.println("AQUI 6 UserController login ");
            if (newAuth.isAuthenticated()) {
                model.addAttribute("usuario", socioServicio.getCurrentUser());
                //rdo = "Estás conectado como" + username;
            } else {
                rdo = "Error al conectar. Comprueba usuario y contraseña";

            }
            //System.out.println("AQUI 7 UserController login ");

        } catch (Exception unfe) {
            rdo = " ERROR " + unfe.getMessage();
            unfe.printStackTrace();
        }
        return rdo;
    }
}
